<template>
  <div>
      <h1 style="text-align:center;">图表封装</h1> 
      <el-button type="success" @click="item.changeCharts" v-for="item in arr" :key="item.id">{{item.name}}</el-button> 
      <MyCharts :option="option" :key="+new Date()"></MyCharts>
  </div>
</template>

<script>  
//封装图表 导入
import MyCharts from '@/components/MyCharts'
import axios from 'axios'

export default {
    //用子组件
  components: {MyCharts},
  data () {
    return {
        option: {},
        arr: [
            {
                id: 1,
                name: '折线图',
                changeCharts: this.lineCharts
            },
            {
                id: 2,
                name: '饼图',
                changeCharts: this.pieCharts
            },
            {
                id: 3,
                name: '柱状图',
                changeCharts: this.barCharts
            },
        ]
      }
    },
    created(){
        //调用方法  可以 .then
        this.getData().then(res => {
            //想要的数据 存起来
            let data = res.data.data
            // console.log(res);
            // console.log(111,data);
            this.data = data
        })
       
    },
  methods: {
        lineCharts() {
            console.log('折线图');
             //给 option 赋值
            this.option = {
                xAxis: {
                data: this.data.map(item => item.year + '年')
                 },
                yAxis: {
                    name:'人数'
                },
                series: [
                    {
                        type: 'line',
                        data: this.data.map(item => item.number) 
                    }
                ]
            }
        },
        pieCharts() {
            console.log('饼图');
            //给 option 赋值
            this.option = {
                series: [
                    {
                        type: 'pie',
                        data: this.data.map(item => {
                            return {
                                name: item.year + '年',
                                value: item.number
                            }
                        }) 
                    } 
                ]
            }
        },
        barCharts() {
            console.log('柱状图');
             //给 option 赋值
            this.option = {
                xAxis: {
                data: this.data.map(item => item.year + '年')
                 },
                yAxis: {
                    name:'人数'
                },
                series: [
                    {
                        type: 'bar',
                        data: this.data.map(item => item.number) 
                    }
                ]
            }
        },
        //定义方法 得到一个promise 对象
        getData() {
           return axios('/data/count')
        }
    }
}
</script>

<style>

</style>
